package com.ruoyi.project.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.DtProduct;
import com.ruoyi.project.system.domain.DtQuery;
import com.ruoyi.project.system.domain.dto.QueryData;
import com.ruoyi.project.system.domain.dto.QueryKeyword;
import com.ruoyi.project.system.mapper.DtFinalResultMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.CacheConstants.DT_RUN_XYHS;

@Service
public class ZeWuService {

    private static final String ZEWU_URL = "https://www.zhichajinkong.com/dataMiddle/api/handle";

    private static final String appId = "3c3ce3eda9ff46b9";

    private static final String appSecret = "283d251782704cdd8ebc0a8e6b5664b5";

    private static final String key = "2c52872066fb89c2ed00c1740ca97b71";

    @Autowired
    private RedisCache rc;

    @Autowired
    private DtFinalResultMapper dfrm;

    public JSONObject getResult(Integer dfrId, DtProduct product, DtQuery query) {
        JSONObject params = new JSONObject();
        List<QueryKeyword> qks = new ArrayList<>();
        String elemDemand = product.getElemDemand();

        String key = "TEM::" + product.getExternalCode();
        if (elemDemand.contains("N")) {
            params.put("name", encrypt(query.getName()));
            key += query.getName();
//            queryKeywords.add(new QueryKeyword(dfrId, "N", query.getName()));
        }
        if (elemDemand.contains("C")) {
            params.put("idCard", encrypt(query.getCardNo()));
            key += query.getCardNo();
//            queryKeywords.add(new QueryKeyword(dfrId, "C", query.getCardNo()));
        }
        if (elemDemand.contains("T")) {
            params.put("phone", encrypt(query.getTel()));
            if ("1".equals(query.getVirtualTel())) {
                qks.add(new QueryKeyword(dfrId, product.getId(), "VT", query.getTel()));
            } else {
                qks.add(new QueryKeyword(dfrId, product.getId(), "N", query.getTel()));
            }
            key += query.getTel();
        }
        if (!qks.isEmpty()) {
            dfrm.insertQueryKeyword(qks);
        }
//        JSONObject info = rc.getCacheObject(key);
        JSONObject info = rc.getCacheObject(key);  // MGZ TODO 2025/9/25: 查询缓存处
        if (info != null) {
            return info;
        }
        params.put("authorized", "1");
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS).build();
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        String encryptedSecret = Md5Utils.hash(appSecret);
        String sign = Md5Utils.hash(encryptedSecret + timestamp);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), params.toJSONString());
        Request request = new Request.Builder()
                .url(ZEWU_URL)
                .post(body)
                .addHeader("appId", appId)
                .addHeader("proId", product.getExternalCode())
                .addHeader("timestamp", String.valueOf(timestamp))
                .addHeader("sign", sign)
                .build();
        // MGZ TODO 2025/8/18: 接口数据请求发起处
        try (Response response = client.newCall(request).execute()) {
            String data = response.body().string();
            System.out.println(key + "::" + data);
            if (StringUtils.isEmpty(data)) {
                return null;
            }
            info = JSON.parseObject(data);
            if ("200".equals(info.getString("code"))) {
                rc.setCacheObject(key, info, 1, TimeUnit.DAYS);
            } else {
                new RuntimeException(info.getString("message"));
            }
            rc.setIncrement(DT_RUN_XYHS + "jkfy", product.getUnitPrice().doubleValue());
            return info;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
//        String result = rc.getCacheObject("TEM::" + query.getCardNo() + "::" + product.getExternalCode());
//        return JSON.parseObject(result);
    }

    //此处为加解密示例代码，请根据实际情况进行修改，其中key为系统中分配的密钥，请在用户中心实名认证后获取
    public static String encrypt(String data) throws SecurityException {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(hexStringConvertBytes(key), "AES");
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(key.substring(0, 16).getBytes("UTF-8"));
            cipher.init(1, keySpec, paramSpec);
            byte[] result = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception var7) {
            throw new SecurityException("加密失败！");
        }
    }

    private static byte[] hexStringConvertBytes(String data) {
        int length = data.length() / 2;
        byte[] result = new byte[length];
        for (int i = 0; i < length; i++) {
            int first = Integer.parseInt(data.substring(i * 2, i * 2 + 1), 16);
            int second = Integer.parseInt(data.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (first * 16 + second);
        }
        return result;
    }

}
